from flask import Flask, request, render_template
import requests
import os
import zipfile

app = Flask(__name__)

def extract_zip(zip_file_path, output_dir):
    with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
        zip_ref.extractall(output_dir)



@app.route('/')
def index():
    return render_template('index.html')






@app.route('/export', methods=['POST'])
def export():
    project_id = request.form.get('projectID')
    token = 'dab1b882a8ebfaf7a1b4a9466e33ef781021e056'
    file_path = 'output'
    file_Name = request.form.get('fileName')

    url = f'http://14.29.241.21:50343/api/projects/{project_id}/export'
    headers = {'Authorization': f'Token {token}'}
    params = {'exportType': 'YOLO', 'download_all_tasks': 'true'}
    if not os.path.exists(file_path):
        os.makedirs(file_path)

    response = requests.get(url, headers=headers, params=params)
    # if response.status_code == 200:
    #     with open(file_path + '/'+file_Name +'.json', 'wb') as file:
    #         file.write(response.content)
    #     return 'JSON content exported successfully.'
    # else:
    #     return 'Error exporting JSON content.'

    if response.status_code == 200:
        file_path = file_path + '/' + file_Name + '.zip'  # 完整的文件路径
        with open(file_path, 'wb') as file:
            file.write(response.content)

        output_dir = 'datasets/output' #替换为解压缩到的目录路径
        extract_zip(file_path,output_dir)

        return f'image content exported successfully. File saved at: {file_path}'
    else:
        return 'Error exporting image content.'

if __name__ == '__main__':
    app.run()